import 'dart:math';
import 'package:demo/config/app_resource.dart';
import 'package:flutter/material.dart';
import 'package:flutter_parsed_text/flutter_parsed_text.dart';
import 'package:get/get.dart';
import 'package:demo/config/app_theme.dart';
import 'package:demo/views/website/website_view.dart';

// 正则表达式
class ToolsRegex {
  // 仅支持数字
  static final regNumber = RegExp("[0-9]");
  // 仅支持数字
  static final regPhone = RegExp("^1[3-9]\\d{9}\$");

  // 是否是手机号
  static bool isPhone(String str) {
    return regPhone.hasMatch(str);
  }

  // 是否网址资源
  static bool isAsset(String asset) {
    if (asset.isEmpty) {
      return false;
    }
    return asset.startsWith(AppImage.path);
  }

  /// 随机生成32位token
  static String token() {
    const String chars = 'abcdefghijklmnopqrstuvwxyzZ0123456789';
    Random random = Random();
    return String.fromCharCodes(
      Iterable.generate(
        32,
        (_) => chars.codeUnitAt(
          random.nextInt(chars.length),
        ),
      ),
    );
  }

  // 转换消息
  static ParsedText parsedText(String text) {
    TextStyle style = TextStyle(color: AppTheme.color, fontSize: 16);
    return ParsedText(
      text: text,
      style: const TextStyle(color: Colors.black, fontSize: 16),
      parse: [
        // 邮箱
        MatchText(
          pattern: r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}',
          style: style,
        ),
        // 网址
        MatchText(
          type: ParsedType.URL,
          style: style,
          onTap: (value) {
            // 打开网址
            Get.toNamed(
              WebsiteView.routeName,
              arguments: ViewData(
                value,
              ),
            );
          },
        ),
        // 手机
        MatchText(
          pattern: r'\b1[3-9]\d{9}\b',
          renderWidget: ({required pattern, required text}) {
            return Text(text, style: style);
          },
          onTap: (value) async {},
        ),
      ],
    );
  }

  static bool disturb(String text, String userId) {
    bool result = text.contains('[0]') || text.contains('[$userId]');
    return !result;
  }
}
